package chat

import (
	"bigmodel/service/chat/spark"
	"context"
	"encoding/json"
	"errors"
	"fmt"

	// "fmt"
	"io"
	"net/http"

	"github.com/swxctx/xlog"
)

// Client 百度API请求客户端
type Spark struct {
	cli spark.Client
}

// NewClient 初始化请求客户端
func NewSpark(appId, apiKey, apiSecret string, debug ...bool) *Spark {
	spark := &Spark{
		cli: *spark.MustNewClient(appId, apiKey, apiSecret, debug...),
	}
	return spark
}

func MustNewSpark(appId, apiKey, apiSecret string, debug ...bool) *Spark {
	e := NewSpark(appId, apiKey, apiSecret, debug...)
	return e
}

func (spark *Spark) Stream(c context.Context, step func(w io.Writer) bool) error {

	return nil
}

func (sp *Spark) Chat(ctx context.Context, resw http.ResponseWriter, args *ChatDoArgsV1,conf string) (*ChatDoResultV1, error) {
	param := &spark.RequestParameterChat{}
	err := json.Unmarshal([]byte(conf),param)
	if err != nil {
		return nil,errors.New(err.Error())
	}
	var temperature float64
	var maxTokens int
	func(){
		maxTokens = 1024
		temperature = 0.7
		if param.Temperature != 0.0 {
			temperature = param.Temperature
		}
		if param.MaxTokens != 0 {
			maxTokens = param.MaxTokens
		}
	}()
	// 正常输出
	streamReader, err := sp.cli.CreateChatStream(args.Model,args.Content,temperature,maxTokens)
	if err != nil {
		xlog.Errorf("chatXF: err-> %v", err)
		return nil, errors.New(err.Error())
	}

	defer streamReader.Close()
	for {
		keepOpen := step(resw, streamReader)
		if !keepOpen {
			break
		}
	}
	return &ChatDoResultV1{
		Message: STREAM_DONE_FLAG,
	}, nil
}

func step(w io.Writer, streamReader *spark.StreamReader) bool {
	data, err := streamReader.ReceiveFormat()
	if err != nil {
		xlog.Errorf("chatXF: Receive err-> %v", err)
		return false
	}
	if streamReader.IsFinish() {
		xlog.Infof("chatXF: receive finish...")
		return false
	}
	if data == nil {
		xlog.Infof("chatXF: line is empty...")
		return true
	}
	content := data.Payload.Choices.Text[0].Content
	// 写入一行数据到响应体
	w.Write(streamResponse(content))
	if flusher, ok := w.(http.Flusher); ok {
		// 确保数据发送到客户端
		flusher.Flush()
	}
	fmt.Println(content)

	// 继续处理下一行
	return true
}
